package com.origin.oss.manager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author yezh
 * @date 2024/2/5 13:53
 */
@Component
public class FileSliceUploadManager {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String FILE_CHUNK_NUMBER = "uploader:file_chunk_num:";

    /**
     * 判断分片是否已经上传过了
     *
     * @param identifier  文件 md5 唯一标识
     * @param chunkNumber 分片号
     * @return true or false
     */
    public boolean checkChunkUploaded(String identifier, int chunkNumber) {
        return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(FILE_CHUNK_NUMBER + identifier, String.valueOf(chunkNumber)));
    }

    /**
     * 分片号存入 redis
     *
     * @param identifier  文件 md5 唯一标识
     * @param chunkNumber 分片号
     */
    public void storeChunkNumber(String identifier, int chunkNumber) {
        redisTemplate.opsForSet().add(FILE_CHUNK_NUMBER + identifier, String.valueOf(chunkNumber));
    }

    /**
     * 检测文件是否有上传过
     */
    public boolean checkFileUploaded(String identifier) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(FILE_CHUNK_NUMBER + identifier));
    }

    public void clearCache(String identifier) {
        redisTemplate.delete(FILE_CHUNK_NUMBER + identifier);
    }

}
